<?php
/*
 * @Description    : 验证码
 * @Author         : QianLong
 * @Date           : 2022-10-08 20:53:52
 * @LastEditors    : QianLong
 * @Site           : http://www.21ds.cn
 * @LastEditTime   : 2024-01-16 17:03:48
 */

namespace App\Service;

use App\Common\RedisCache;
use Yurun\Util\HttpRequest;

class BdCloud
{
    protected $config;
    protected $http;
    public function __construct($config,$isAll = false)
    {
        $this->config = $config;
        $this->http = new HttpRequest;
        if ($isAll == false) {
            if (isset($this->config['ak_from']) && $this->config['ak_from'] == 'platform' && isset($this->config['ak_id']) && !empty($this->config['ak_id'])) {
                $akInfo = (new RedisCache)->getAk($this->config['ak_id'], $this->config['uid']);
                unset($akInfo['_id']);
                $this->config = array_merge($this->config, $akInfo);
                unset($akInfo);
            }
        }
    }
    public function doRequest($url, $method, $service, $region, $content)
    {
        // $jsonBody = json_encode($contractData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        if ($method == 'POST') {
            $jsonBody = (is_array($content))?json_encode($content, JSON_UNESCAPED_UNICODE): $content;
        } else {
            $jsonBody = $content;
        }
        $parseUrl = parse_url($url);
        $path = $this->encodeStr($parseUrl['path']);
        $timestamp = gmdate("Ymd\THis\Z");
        $canonicalHeaders['x-jdcloud-date'] = $timestamp;
        $canonicalHeaders['host'] = $parseUrl['host'];
        $canonicalHeaders['content-type'] = 'application/json';
        $canonicalHeaders['x-jdcloud-algorithm'] = 'JDCLOUD2-HMAC-SHA256';
        $canonicalHeaders['x-jdcloud-nonce'] = createId();
        $signerHeaders = ['host', 'x-jdcloud-date','x-jdcloud-nonce'];
        $query = isset($parseUrl['query']) ? $parseUrl['query'] : '';
        $canonicalHeaders['authorization'] = $this->createSignature($this->config['jdcloud_access_key_id'], $this->config['jdcloud_access_key_secret'], $timestamp, $region, $service, $method, $path, $query, $canonicalHeaders, $signerHeaders, $jsonBody);
        if ($method == 'POST') {
            $response = $this->http->headers($canonicalHeaders)->post($url, $jsonBody,'json');
        } else {
            $response = $this->http->headers($canonicalHeaders)->get($url, $jsonBody);
        }
        $requestResult = json_decode($response->body(), true);
        return $requestResult;
    }
    public function encodeStr($str){
        $str = str_replace(':','%3A', $str);
        return $str;
    }
    public function generateAuthString($accessKeyId, $secretAccessKey, $httpMethod, $canonicalURI, $canonicalQueryString, $canonicalHeaders, $timestamp, $expirationPeriodInSeconds)
    {
        // 任务一：创建前缀字符串
        $authStringPrefix = "bce-auth-v1/{$accessKeyId}/{$timestamp}/{$expirationPeriodInSeconds}";

        // 任务二：创建规范请求
        $canonicalRequest = "{$httpMethod}\n{$canonicalURI}\n{$canonicalQueryString}\n{$canonicalHeaders}";

        // 任务三：生成派生签名密钥
        $signingKey = hash_hmac('sha256', $authStringPrefix, $secretAccessKey);

        // 任务四：生成签名摘要
        $signature = hash_hmac('sha256', $canonicalRequest, $signingKey);

        // 拼接最终的认证字符串
        $authorization = "{$authStringPrefix}/{$signature}";

        return $authorization;
    }
    public function generateAuthStringV2($accessKeyId, $secretAccessKey, $httpMethod, $canonicalURI, $canonicalQueryString, $canonicalHeaders, $date, $region, $service)
    {
        // 创建规范请求
        $canonicalRequest = "{$httpMethod}\n{$canonicalURI}\n{$canonicalQueryString}\n{$canonicalHeaders}";

        // 认证字符串的前缀部分
        $authStringPrefix = "bce-auth-v2/{$accessKeyId}/{$date}/{$region}/{$service}";

        // 生成派生签名密钥
        $signingKey = hash_hmac('sha256', $authStringPrefix, $secretAccessKey);

        // 生成签名摘要
        $signature = hash_hmac('sha256', $canonicalRequest, $signingKey);

        // 拼接最终的认证字符串
        $authorization = "{$authStringPrefix}/{$signature}";

        return $authorization;
    }
}